import { ref, onBeforeUnmount } from 'vue';

const layers = {};

function installLayer(name, baseline, capacity) {
	if (layers[name]) return false;
	const newLayer = {
		name, baseline, capacity,
		children: {},
		lastIndex: baseline
	}
	layers[name] = newLayer
	return newLayer;
}

installLayer('default', 1200, 300);

function useZIndex(name = 'default', baseline, capacity) {
	
	const zIndex = ref();
	const alive = ref(false);
	
	const layer = layers[name] || installLayer(name, baseline, capacity);
	const id = Symbol();
	
	onBeforeUnmount(() => {
		resolveZIndex();
	})

	function nextZIndex() {
		const range = layer.baseline + layer.capacity;
		if (layer.lastIndex + 1 >= range) {
			const list = Object.getOwnPropertySymbols(layer.children);
			list.map(item => layer.children[item])
				.sort((a, b) => a.updateTime - b.updateTime)
				.forEach((item, index) => {
					item.zIndex.value = layer.baseline + index;
				})
			layer.lastIndex = layer.baseline + list.length - 2;
		}
		zIndex.value = ++layer.lastIndex;
		alive.value = true;
		layer.children[id] = {
			zIndex,
			updateTime: new Date()
		};
	}
	
	function resolveZIndex() {
		if (layer.children[id]) {
			delete layer.children[id];
			alive.value = false
		}
	}
	
	return {
		zIndex,
		alive,
		nextZIndex,
		resolveZIndex
	}
	
}

export default useZIndex;